package com.woniuxy.nio.channel.filechannel;

import com.woniuxy.nio.util.FileUtils;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 通过 FileChannel 读取数据到buffer中
 * <P> Date: 2022/4/3:10:26
 * <P> Description:
 */

public class FileChannelReadDemo1 {
    public static void main(String[] args) throws Exception {
        //TODO 1.创建FileChannel
        RandomAccessFile accessFile =
                new RandomAccessFile(FileUtils.FILE_TARGET, "rw");
        FileChannel channel = accessFile.getChannel();

        //TODO 2.创建Buffer 定义一次读取的长度buffer长度
        ByteBuffer buf = ByteBuffer.allocate(100);

        //TODO 3.读取数据到buffer中
        int read;
        while ((read = channel.read(buf)) != -1) {
            System.out.println("读取了长度：" + read);
            //TODO 转换状态 这里转为从buffer中取出
            //TODO 把limit设为当前position，把position设为0，一般在从Buffer读出数据前调用
            buf.flip();

            //TODO 把这次buffer中读入的数据读取出来  hasRemaining()是否读取完
            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            buf.clear();
        }

        channel.close();
        accessFile.close();

    }
}
